package cn.lysj.framework.common.validate.validate;

import cn.lysj.framework.common.CommonConstant;
import cn.lysj.framework.common.utils.spring.SpringContextUtil;
import cn.lysj.framework.common.validate.Message;
import cn.lysj.framework.common.validate.annotation.Unique;
import cn.lysj.framework.common.validate.entity.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

public class UniqueValidate extends AbstractValidate<Unique> {

    private EntityManager em;

    /**
     * @author ww
     * @date 2018-08-19 14:04
     * @Description 判断参数中是否有存在ID
     */
    public boolean validate(Entity entity){
        em = SpringContextUtil.getBean(EntityManager.class);
        StringBuilder sb = new StringBuilder();
        if(Message.id != null){
//            return true;
            return getIdMsg(sb,entity);
        }else{
            return getUnique(sb,entity);
        }
    }

    /**
     * @author ww
     * @date 2018-08-19 14:05
     * @Description 没有ID，就判断字段的唯一性
     */
    public boolean getUnique(StringBuilder sb,Entity entity){
        sb.append("select count(*) from ")
                .append(entity.getClazz().getSimpleName())
                .append(" t where t.")
                .append(entity.getField().getName())
                .append("= ? and t.delFlag = ")
                .append(CommonConstant.NORMAL_FLAG);
        Query query = em.createQuery(sb.toString(),Long.class).setParameter(1,entity.getValue());
        Long count = (Long) query.getSingleResult();
        if(count != null && count <= 0){
            return true;
        }
        return false;
    }

    /**
     * @author ww
     * @date 2018-08-19 14:05
     * @Description 有ID，先判断字段是否有改动，没改动则跳过，否则就判断唯一性
     */
    public boolean getIdMsg(StringBuilder sb,Entity entity){
        sb.append("select t."+entity.getField().getName())
                .append(" from "+entity.getClazz().getSimpleName())
                .append(" t where t.id")
                .append("= ? and t.delFlag = ")
                .append(CommonConstant.NORMAL_FLAG);
        Query query = em.createQuery(sb.toString(),entity.getField().getType()).setParameter(1,Message.id);
        try {
            if(query.getResultList().get(0).toString().equals(entity.getValue())){
                return true;
            }else{
                StringBuilder sbd = new StringBuilder();
                return getUnique(sbd,entity);
            }
        }catch (Exception e){
            return true;
        }
    }

    public void init() {
        this.setMsg(annotation.message());
        this.setGroups(annotation.groups());
    }
}
